{% extends "./template.html" %}

{% block body %}
<div class="mb-4 mt-4">
    <div class="d-flex justify-content-center" id="alert-box">
        <div class="alert d-none" id="alert" style="width:30%">
            <h6 class="alert-heading">提示</h6>
            <p class="alert-body"></p>
        </div>
    </div>
    <div class="d-flex justify-content-center align-items-center">
        <div class="col-md-5">
            <div class="text-center">
                <h4>登录</h4>
            </div>
            <form>
                <div class="form-group">
                    <label for="useraname">用户名</label>
                    <input type="email" class="form-control" id="username" aria-describedby="emailHelp">
                </div>
                <div class="form-group">
                    <label for="password">密码</label>
                    <input type="password" class="form-control" id="password">
                </div>
                <div class="d-flex justify-content-between">
                    <button type="button" id="submit-btn" class="btn btn-primary">登录</button>
                </div>
            </form>
        </div>
    </div>
</div>
{% endblock %}

{% block script %}
<script src="script/index.js"></script>
<script type="module">
    window.onload = () => {
        const submitBtn = document.querySelector('#submit-btn');
        submitBtn.addEventListener('click', () => {
            const username = document.querySelector('#username').value;
            const password = document.querySelector('#password').value;
            if (username == '') {
                checkMsg({ msg: '用户名不能为空', type: 'warning' })
                return;
            }
            if (password == '') {
                checkMsg({ msg: '密码不能为空', type: 'warning' })
                return;
            }
            $.ajax({
                method: 'post',
                url: '/api/login',
                data: {
                    username,
                    password
                },
                success: res => {
                    if (res.code == 200) {
                        let user = res.data.user;
                        localStorage.setItem('user_id', user.id);
                        localStorage.setItem('isLogin', true);
                        localStorage.setItem('token', user.token);
                        window.location = `/?user_id=${user.id}`
                    } else {
                        if (password == '') {
                            checkMsg({ msg: '密码不能为空', type: 'warning' })
                            return;
                        }
                    }
                },
                fail: (err) => {
                    console.log(err);
                }
            })
        })
    }
</script>
{% endblock %}